package com.zmm.member.controller;

import com.alibaba.fastjson.JSON;
import com.zmm.common.constant.RedisTimeOutConstant;
import com.zmm.common.enums.TokenType;
import com.zmm.common.redis.key.CommonKey;
import com.zmm.member.model.AuthToken;
import com.zmm.member.model.Customer;
import com.zmm.member.service.CustomerService;
import com.zmm.util.auth.model.Operator;
import com.zmm.util.auth.model.Token;
import com.zmm.util.auth.model.UserForAuth;
import com.zmm.util.redis.RedisUtil;
import com.zmm.util.token.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 登陆类
 * @author 900045
 * @description:
 * @name LoginController
 * @date By 2021-07-26 11:02:43
 */
@Slf4j
public abstract class LoginController {

	@Autowired
	private CustomerService customerService;

	@Resource
	protected Operator operator;

	@Resource
	protected RedisUtil redisUtil;

	/**
	 * 退出操作
	 * @author: 900045
	 * @date: 2021-07-26 14:24:13
	 * @throws 
	 * @return: void
	 **/
	protected void doLogout() {
		UserForAuth user = operator.fetchUser();
		TokenType tokenType = TokenType.CUSTOMER;
		if (user.getServiceEr()) {
			tokenType = TokenType.SERVICE_ER;
		}
		String userIdStr = TokenUtil.generateCustomerId(user.getUserId(), tokenType);
		Object hash = redisUtil.hash(CommonKey.AUTH_USER_KEY,userIdStr);
		if (!ObjectUtils.isEmpty(hash)){
			UserForAuth redisUser = JSON.parseObject(JSON.toJSONString(hash), UserForAuth.class);
			//redisUtil.hashDelete(CommonKey.AUTH_USER_KEY, userIdStr)
			redisUtil.delete(CommonKey.AUTH_TOKEN_REFRESH_PREFIX.setSuffix(redisUser.getRefreshToken()));
			redisUtil.delete(CommonKey.AUTH_TOKEN_USER_PREFIX.setSuffix(redisUser.getAccessToken()));
		}
	}


	/**
	 * 生成会员token
	 * @author: 900045
	 * @date: 2021-07-26 14:44:45
	 * @throws 
	 * @param customer: 
	 * @return: com.zmm.util.auth.model.Token
	 **/
	protected Token getToken(Customer customer,Integer accountType) {
		//缓存模型
		UserForAuth userAuth = new UserForAuth();
		userAuth.setServiceEr(false);
		userAuth.setUserId(customer.getCustomerId());
		userAuth.setUserName(customer.getCustomerUsername());
		String userIdStr = TokenUtil.generateCustomerId(userAuth.getUserId());
		//写入缓存 放置 generateToken 中
		// redisUtil.hash(CommonKey.AUTH_USER_KEY, userIdStr, userAuth)
		Token token = generateToken(userIdStr, userAuth, customer.getLoginIp(), accountType);
		token.setUserId(customer.getCustomerId());
		token.setUserName(customer.getCustomerUsername());
		token.setMobile(customer.getCustomerUsername());
		return token;
	}

	/**
	 * 生成token
	 * @author: 900045
	 * @date: 2021-07-26 14:44:23
	 * @throws 
	 * @param userIdOfToken: 
	 * @param userAuth:   
	 * @param loginIp:   
	 * @return: com.zmm.util.auth.model.Token
	 **/
	protected Token generateToken(String userIdOfToken, UserForAuth userAuth, String loginIp, Integer accountType) {
		Token token = new Token();
		long currentTimeMillis = System.currentTimeMillis();
		String tokenVal = UUID.randomUUID().toString();
		// 10天   毫秒数
		long tokenExpires = currentTimeMillis + RedisTimeOutConstant.S_86400 * 10 * 1000;
		//二天
		redisUtil.set(CommonKey.AUTH_TOKEN_USER_PREFIX.setSuffix(tokenVal), userIdOfToken, tokenExpires, TimeUnit.MILLISECONDS);
		String refreshToken = UUID.randomUUID().toString();
		// 30天  毫秒数
		long refreshExpires = currentTimeMillis + RedisTimeOutConstant.S_86400 * 30 * 1000;
		// 三十天
		redisUtil.set(CommonKey.AUTH_TOKEN_REFRESH_PREFIX.setSuffix(refreshToken), userIdOfToken, refreshExpires, TimeUnit.MILLISECONDS); 
		token.setAccessToken(tokenVal);
		token.setTokenExpires(tokenExpires);
		token.setRefreshToken(refreshToken);
		token.setRefreshExpires(refreshExpires);
		//写入缓存 添加缓存的过期时间
		userAuth.setAccessToken(tokenVal);
		userAuth.setRefreshToken(refreshToken);
		redisUtil.hash(CommonKey.AUTH_USER_KEY, userIdOfToken, userAuth);
		try {
			AuthToken authToken = new AuthToken();
			authToken.setCustomerId(userAuth.getUserId());
			authToken.setLoginIp(loginIp);
			authToken.setAdmin(accountType);
			authToken.setAccessToken(tokenVal);
			authToken.setRefreshToken(refreshToken);
			customerService.addAuthToken(authToken);
		} catch (Exception e) {
			log.error("添加用户token 失败!!!!");
		}
		log.error("***GENERATE-TOKEN*************: {}, {}, {} ", userIdOfToken, tokenVal, token);
		return token;
	}
}
